package com.ht.medicaltreatment.activity

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.forEach
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.gym.baselib.base.BaseActivity
import com.gym.baselib.utils.CacheUtils
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.MultiSampleCollectionAdapter
import com.ht.medicaltreatment.base.CacheKey
import com.ht.medicaltreatment.bean.Drawblood
import com.ht.medicaltreatment.utils.BloodScanErrorDialog
import com.ht.medicaltreatment.utils.DownTimeUtils
import com.ht.medicaltreatment.utils.NFCUtils
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.utils.UIDUitls
import com.ht.medicaltreatment.view.BloodRemarkDialog
import com.ht.medicaltreatment.view.ReplaceCaiXueDialog
import com.ht.medicaltreatment.viewmodel.SingleViewModel
import com.xgst.lib.utils.showToast
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.groupHY
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.groupHYState
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgCYD
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgJump
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgNext
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgRed
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgScan
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgStation
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.imgTH
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.llRemarks
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.llStartTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.progress
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.progressGroup
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.recyclerView
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvAfterTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvCode
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvDownTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvLJCY
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvName
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvPlanCXTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvPlanTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvPreTime
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvSex
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvStartCheck
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvStation
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvTubeName
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvUserName
import kotlinx.android.synthetic.main.activity_multi_sample_collection_detail_layout.tvYear
import kotlinx.android.synthetic.main.item_send_list_layout.tvS
import java.text.SimpleDateFormat

/**
 * 多管 患者采血
 */
class MultiSampleCollectionDetailActivity : BaseActivity(), View.OnClickListener {

    override fun getLayoutId() = R.layout.activity_multi_sample_collection_detail_layout

    private lateinit var adapter: MultiSampleCollectionAdapter
    private val model by viewModels<SingleViewModel>()
    private var isNFC = false
    private lateinit var replaceCaiXueDialog: ReplaceCaiXueDialog

    //前时间窗 分钟
    private var preTimeMinute = 0f

    //后时间窗 分钟
    private var afterTimeMinute = 0f
    private var orderId = 0
    private var isAllChecked = false
    private var isCaiXue = false
    private var isReplace = false

    //后时间窗
    private var afterTime = 0L

    //前时间窗
    private var preTime = 0L
    private var planTime: Long = 0L
    private var checkSuccess = 0
    private var drawBloodOrderId = 0
    private var drawBloodId = 0
    private var isOpen = false
    private lateinit var mediaplayer: MediaPlayer
    private var disposable: Disposable? = null
    private var disposable2: Disposable? = null
    private var disposable3: Disposable? = null
    //用来记录是否点击过【点击核验】按钮，如果没有点击过，那么就不要校验是否记录采样时间了
    private var isHasClick = false


    //来自条形码
    private var isBarCode = false
    private var expectTime: String? = ""

    override fun init() {
        setTitle("样本采集")

        mediaplayer = MediaPlayer.create(this, R.raw.after_collection_blood30)
        mediaplayer.setLooping(false)

        tvUserName.text = CacheUtils.getStringCache(CacheKey.NAME)

        val uid = intent.getStringExtra("uid") ?: ""
        val isOrder = intent.getBooleanExtra("isOrder", false)
        replaceCaiXueDialog = ReplaceCaiXueDialog(this)
        adapter = MultiSampleCollectionAdapter()
        recyclerView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        recyclerView.adapter = adapter

        initClick()

        if (Build.MODEL == "V9100") {
            ScanUtils.init()
        } else {
            isNFC = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)
            if (isNFC) {
                NFCUtils(this)
            }
        }

        val drawbloodList = intent.getParcelableArrayListExtra<Drawblood>("bloodList")

        if (drawbloodList != null && drawbloodList.size > 0) {
            adapter.setNewInstance(drawbloodList)

            val it = drawbloodList!![0]
            tvName.text = it.patientInformation?.patientName
            tvSex.text = it.patientInformation?.patientSex
            tvCode.text = it.patientInformation?.patientCode
            val sb = StringBuilder()
            drawbloodList.forEachIndexed { index, drawblood ->
                if (index != drawbloodList.size - 1) {
                    sb.append(drawblood.name)
                    sb.append("\n")
                } else {
                    sb.append(drawblood.name)
                }
            }
            tvTubeName.text = sb.toString()
            orderId = it.drawbloodMoreOrder?.id ?: 0

            initView(it)
        } else {
            model.wanDai(uid, isOrder, {
                tvName.text = it.patientInformation.patientName
                tvSex.text = it.patientInformation.patientSex
                tvCode.text = it.patientInformation.patientCode
                orderId = it.drawBloodMoreOrder?.id ?: 0
                it.patientInformation.ward.remarks
                //每个时间点只有一根试管
                if (it.drawBloodMoreOrder?.bloodNum == 1) {
                    val item = it.drawbloodList.first { it.checkSuccess == 0 }
                    adapter.addData(item)
                    tvTubeName.text = item.name
                    initView(item)
                    LogUtils.i("一个的",it.drawbloodList.size)
                } else {
                    LogUtils.i("多个的",it.drawbloodList.size)
                    //多管
                    val drawbloodList = it.drawbloodList
                    var startIndex = 0
                    //当前时间点
                    while (startIndex < drawbloodList.size) {
                        var over = false
                        val bloodGroupSum = drawbloodList[startIndex].bloodGroupSum
                        //当前时间点的管
                        for (i in 0 until bloodGroupSum) {
                            if (i + startIndex >= it.drawbloodList.size) return@wanDai
                            val drawblood = it.drawbloodList[i + startIndex]
                            if (drawblood.checkSuccess == 0) {
                                over = true
                            }
                            adapter.addData(drawblood)
                        }
                        //都不为0的话，表示没有需要采血的管子
                        if (over) {
                            val sb = StringBuilder()
                            adapter.data.forEachIndexed { index, drawblood ->
                                if (index != drawbloodList.size - 1) {
                                    sb.append(drawblood.name)
                                    sb.append("\n")
                                } else {
                                    sb.append(drawblood.name)
                                }
                            }
                            tvTubeName.text = sb.toString()

                            initView(adapter.data[0])
                            return@wanDai
                        }
                        adapter.data.clear()
                        startIndex = startIndex + bloodGroupSum
                    }
                }
            }, {
                showToast(it)
            })
        }
    }

    private fun initView(item: Drawblood) {
        drawBloodOrderId = item.drawbloodMoreOrder?.id ?: 0
        drawBloodId = item.id
        preTimeMinute = item.preTimeStamp?.toFloat() ?: 0f
        afterTimeMinute = item.afterTimeStamp?.toFloat() ?: 0f

        //红点位置
        redLocation()

        expectTime = item.expectTime
        tvPreTime.text = item.preTimeStamp
        tvAfterTime.text = item.afterTimeStamp
        tvPlanTime.text = expectTime

        //计划采血时间
        planTime = TimeUtils.string2Millis(expectTime, "yyyy-MM-dd HH:mm:ss")
        preTime = planTime - (preTimeMinute * 60 * 1000).toInt()
        afterTime = planTime + (afterTimeMinute * 60 * 1000).toInt()
        //LogUtils.i("initView",TimeUtils.getNowMills(),planTime,preTime,afterTime)

        checkSuccess = item.checkSuccess

        if (checkSuccess == 1) {
            //回显 - 核验正常，并且已经采血
            groupHY.visibility = View.GONE
            groupHYState.visibility = View.VISIBLE

            imgStation.setBackgroundResource(R.drawable.icon_heyan_success)
            tvStation.text = "采样正常"
            tvStation.setTextColor(getColor(R.color.green))

            tvPlanCXTime.text = "计划采血时间:${tvPlanTime.text}"
            progressGroup.visibility = View.INVISIBLE
            imgRed.visibility = View.GONE
        } else if (checkSuccess == 2) {
            // 回显 - 已超窗
            groupHY.visibility = View.GONE
            groupHYState.visibility = View.VISIBLE

            imgStation.setBackgroundResource(R.drawable.icon_chaochuang)
            tvStation.text = "采样超窗"
            tvStation.setTextColor(getColor(R.color.red))

            tvPlanCXTime.text = "计划采血时间:${tvPlanTime.text}"
            progressGroup.visibility = View.INVISIBLE
            imgRed.visibility = View.GONE

        } else if (checkSuccess == 3) {
            //回显 - 紧急跳过
            groupHY.visibility = View.GONE
            groupHYState.visibility = View.VISIBLE

            imgStation.setBackgroundResource(R.drawable.icon_jjtg)
            tvStation.text = "紧急跳过"
            tvStation.setTextColor(getColor(R.color.orange))

            progressGroup.visibility = View.INVISIBLE
            imgRed.visibility = View.GONE

        }

        //1、原来的方案：进入页面就开始倒计时，第一个倒计时是距离前时间窗的倒计时，第二个倒计时是距离后时间窗的倒计时
        //2、2024.4.26方案，核验成功后 再开始倒计时，第一个倒计时是距离前时间窗的倒计时，第二个是距离采血时间的倒计时，第三个是距离后时间窗的倒计时
        /*if(checkSuccess == 0){
            startDownTime(expectTime)
        }*/

        //多少根试管就添加多少个 备注按钮 和 采血按钮
        adapter.data.forEach { item ->
            val remark =
                LayoutInflater.from(this).inflate(R.layout.include_remark_layout, null, false)
            val blood = LayoutInflater.from(this)
                .inflate(R.layout.include_collection_blood_layout, null, false)
            remark.findViewById<TextView>(R.id.tvInputMark).text = "点击添加备注信息\n${item.name}"
            remark.tag = item.name
            blood.tag = item.name

            val tvStartTime = blood.findViewById<TextView>(R.id.tvStartTime)
            if (item.actualTime != null) {
                tvStartTime.text = "采血时间: ${item.actualTime}\n${item.name}"
                tvStartTime.setTextColor(getColor(R.color.color97))
            } else {
                tvStartTime.text = "点击记录采样时间\n${item.name}"
            }

            //TODO 备注按钮的点击事件
            remark.setOnClickListener {
                BloodRemarkDialog(this).show(item.otherRemark ?: "") { etRemark ->
                    //发送备注信息
                    showProgress()
                    model.updateDrawblood("${item.id}", etRemark) {
                        dismissProgress()
                        showToast("备注成功")
                    }
                }
            }

            //TODO 点击记录采血时间  采血按钮的点击事件
            blood.setOnClickListener {
                if (tvStation.text.toString() == "紧急跳过") {
                    showToast("已跳过，无法采血")
                    return@setOnClickListener
                }
                if (!isCheckAll()) {
                    showToast("您还未完成核验")
                    return@setOnClickListener
                }
                val tvStartTime = blood.findViewById<TextView>(R.id.tvStartTime)

                if (checkSuccess == 1 || checkSuccess == 2) {
                    showToast("已记录采血时间，无需重复记录")
                    return@setOnClickListener
                }

                if (checkSuccess == 3) {
                    showToast("已紧急跳过")
                    return@setOnClickListener
                }

                //如果都记录完采样时间了，那么就关闭定时器
                var checkCount = 0
                llStartTime.forEach { childView ->
                    val tvStartTime = childView.findViewById<TextView>(R.id.tvStartTime)
                    LogUtils.i(tvStartTime.text)
                    if(tvStartTime.text.toString().contains("采血时间")){
                        checkCount++
                    }
                }
                if(checkCount == llStartTime.childCount){
                    disposable?.dispose()
                    disposable2?.dispose()
                    disposable3?.dispose()
                }

                if (TimeUtils.getNowMills() < preTime || TimeUtils.getNowMills() > afterTime) {
                    //超窗,必须填写备注才可以记录采血时间
                    SoundUtils.playSound(SoundUtils.OUT_OF_WINDOW)
                    BloodRemarkDialog(this).show(item.otherRemark ?: "") { remark ->
                        val nowTime = TimeUtils.getNowString()
                        showProgress()
                        model.addRemarks(nowTime, "${item.id}", remark) {
                            dismissProgress()
                            //修改试管颜色为采血颜色
                            adapter.data.find { it.checkSuccess != 4 }?.checkSuccess = 4
                            adapter.notifyDataSetChanged()

                            tvStartTime.text = "采血时间:$nowTime\n${item.name}"
                            tvStartTime.setTextColor(getColor(R.color.color97))
                            collectBloodTime()
                        }
                    }
                } else {
                    //没有超窗  记录采血时间
                    showProgress()
                    model.bloodCollectionTime(TimeUtils.getNowString(), "${item.id}") {
                        dismissProgress()
                        if (!tvStartTime.text.contains("采血时间")) {
                            tvStartTime.text = "采血时间:${TimeUtils.getNowString()}\n${item.name}"
                            tvStartTime.setTextColor(getColor(R.color.color97))
                            collectBloodTime()
                        }
                    }
                    //修改试管颜色为采血颜色
                    adapter.data.find { it.checkSuccess != 4 }?.checkSuccess = 4
                    adapter.notifyDataSetChanged()
                }
            }

            llRemarks.addView(remark)
            llStartTime.addView(blood)
        }
    }

    /**
     * 开始执行进度条
     */
    private fun executeProgress(offsetTime: Long) {
        val maxTime = (afterTime - preTime) / 1000
        val downTime = (afterTime - TimeUtils.getNowMills()) / 1000
        tvLJCY.text = "请立即采样"
        progress.setMaxProgress(maxTime.toFloat())
        //偏移量
        //val offsetTime = (TimeUtils.getNowMills() - preTime)/1000
        //进度条开始执行
        disposable2 = DownTimeUtils.downTime(downTime) {
            progress.setProgress(offsetTime + (downTime - it).toFloat())
            /*if(it == 33L){
                //距离超窗还有30秒
                mediaplayer = MediaPlayer.create(this,R.raw.after_outof_window30)
                mediaplayer.start()
            }

            if(it == 0L){
                //已经超窗
                mediaplayer = MediaPlayer.create(this,R.raw.outof_window)
                mediaplayer.start()
            }*/
        }
    }

    /**
     * 开始执行倒计时计划
     */
    private fun startDownTime() {
        if (disposable?.isDisposed == false) {
            disposable?.dispose()
        }
        if (disposable2?.isDisposed == false) {
            disposable2?.dispose()
        }
        if (disposable3?.isDisposed == false) {
            disposable3?.dispose()
        }

        if (preTime - TimeUtils.getNowMills() > 0) {
            LogUtils.i("当前时间 还没有到达前时间窗呢")
            //这个地方是，当前时间小于前时间窗 （就是还没有到前时间窗这个时间点） （备注：还没有到达前时间窗呢就开始采血了，也就是提前采血了，也叫超窗）
            tvLJCY.text = "还未到采样时间"
            /**
             * 1、设置最大进度是  前时间窗 -> 后时间窗之间的距离
             * 2、第一个倒计时是  当前时间 -> 前时间窗 (距离开始采血的时间)
             * 3、第二个倒计时是  前时间窗 -> 计划采血时间
             * 4、第三个倒计时   计划采血时间 -> 后时间窗 （距离超窗的时间）
             * 5、红点的位置     计划时间 距离前时间窗的距离  占据这个进度的百分比
             */
            val currentTime = TimeUtils.getNowMills()
            /* //1、设置最大进度
             val maxProgress = (afterTime - preTime)/1000
             progress.setMaxProgress(maxProgress.toFloat())*/
            //2、第一个倒计时是  当前时间 -> 前时间窗 (距离前时间窗的时间)
            disposable = DownTimeUtils.downTime((preTime - currentTime) / 1000, {
                tvDownTime.text = "$it"
                if (it == 0L) {
                    //到达前时间窗位置
                    mediaplayer = MediaPlayer.create(this, R.raw.window_begin)
                    mediaplayer.start()
                    tvLJCY.text = "请立即采样"

                    //到达了前时间窗，进度条开始执行 ,这个时候我从0开始执行的，没有偏移量
                    executeProgress(0)

                    //第二个倒计时
                    val downTime2 = (planTime - TimeUtils.getNowMills()) / 1000
                    disposable2 = DownTimeUtils.downTime(downTime2, {
                        tvDownTime.text = "$it"

                        if (it == 36L) {
                            mediaplayer =
                                MediaPlayer.create(this, R.raw.after_collection_blood30)
                            mediaplayer.start()
                        }

                        if (it == 3L) {
                            mediaplayer =
                                MediaPlayer.create(this, R.raw.collection_blood)
                            mediaplayer.start()
                        }

                        if (it == 0L) {
                            //第三个倒计时
                            val downTime3 = (afterTime - TimeUtils.getNowMills()) / 1000
                            disposable3 = DownTimeUtils.downTime(downTime3, {
                                tvDownTime.text = "$it"
                                if (it == 36L) {
                                    //距离超窗还有30秒
                                    mediaplayer =
                                        MediaPlayer.create(this, R.raw.after_outof_window30)
                                    mediaplayer.start()
                                }

                                if (it == 3L) {
                                    //已经超窗
                                    mediaplayer = MediaPlayer.create(this, R.raw.outof_window)
                                    mediaplayer.start()
                                }
                            })
                        }
                    })
                }
            })
        } else if (TimeUtils.getNowMills() > preTime && TimeUtils.getNowMills() < planTime) {
            //当前时间处于前时间窗和计划时间之间
            LogUtils.i("当前时间处于前时间窗和计划时间之间")
            //没超窗
            SoundUtils.playSound(SoundUtils.WINDOW_BEGIN)
            //执行进度条
            val offsetTime = (TimeUtils.getNowMills() - preTime) / 1000
            executeProgress(offsetTime)
            //当前时间还没有超过计划时间 (下面这个倒计时是当前时间到计划时间的距离)
            disposable = DownTimeUtils.downTime((planTime - TimeUtils.getNowMills()) / 1000) {
                tvDownTime.text = "$it"
                //距离计划采血时间还剩35秒的时候，开始播报语音提示还剩30秒，播报完语音正好还剩30秒
                if (it == 35L) {
                    mediaplayer = MediaPlayer.create(this, R.raw.after_collection_blood30)
                    mediaplayer.start()
                }
                //进入到计划采血时间，提示用户立即采样
                if (it == 0L) {
                    mediaplayer = MediaPlayer.create(this, R.raw.collection_blood)
                    mediaplayer.start()
                    disposable!!.dispose()

                    //到达计划时间后，开始执行计划时间到后时间窗的倒计时
                    disposable = DownTimeUtils.downTime((afterTime - TimeUtils.getNowMills()) / 1000) {
                            tvDownTime.text = "$it"
                            if (it == 33L) {
                                //距离超窗还有30秒
                                mediaplayer = MediaPlayer.create(this, R.raw.after_outof_window30)
                                mediaplayer.start()
                            }

                            if (it == 0L) {
                                //已经超窗
                                mediaplayer = MediaPlayer.create(this, R.raw.outof_window)
                                mediaplayer.start()
                            }
                        }
                }
            }
        }else if(TimeUtils.getNowMills() > planTime && TimeUtils.getNowMills() < afterTime){
            LogUtils.i("当前时间超过了计划时间")
            //当前时间超过了计划时间
            val offsetTime = (TimeUtils.getNowMills() - preTime) / 1000
            executeProgress(offsetTime)
            disposable = DownTimeUtils.downTime((afterTime - TimeUtils.getNowMills()) / 1000) {
                tvDownTime.text = "$it"
                if (it == 33L) {
                    //距离超窗还有30秒
                    mediaplayer = MediaPlayer.create(this, R.raw.after_outof_window30)
                    mediaplayer.start()
                }

                if (it == 0L) {
                    //已经超窗
                    mediaplayer = MediaPlayer.create(this, R.raw.outof_window)
                    mediaplayer.start()
                }
            }
        }else if(TimeUtils.getNowMills() > afterTime){
            //当前时间大于
            LogUtils.i("当前时间超过了后时间窗")
            //超窗
            tvLJCY.text = "已超窗"
            tvLJCY.setTextColor(Color.RED)
            tvDownTime.text = "0"
            progress.setMaxProgress(1f)
            progress.setProgress(1f)
        }
    }

    private fun redLocation() {
        if (preTimeMinute == 0f) return
        //红点位置
        val percent: Float = preTimeMinute / (preTimeMinute + afterTimeMinute)
        val left: Float = percent * progress.width
        val params = imgRed.layoutParams as ConstraintLayout.LayoutParams
        params.leftMargin = left.toInt() - imgRed.width / 2
        imgRed.layoutParams = params
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        //红点位置
        redLocation()
    }

    private fun initClick() {
        imgTH.setOnClickListener(this)
        tvStartCheck.setOnClickListener(this)
        imgJump.setOnClickListener(this)
        imgNext.setOnClickListener(this)
        imgScan.setOnClickListener(this)
        imgCYD.setOnClickListener(this)
    }

    /**
     * 是否超窗：是否超过后时间窗
     * true  超窗
     * fasle 没有
     */
    /*fun isOver():Boolean{
        val countTime = TimeUtils.getNowMills()
        preTime = planTime - (preTimeMinute*60*1000).toInt()
        afterTime = planTime + (afterTimeMinute*60*1000).toInt()
        LogUtils.i(planTime,preTime,afterTime)
        val isOver = !(countTime > preTime && countTime < afterTime)
        //是否超窗
        return isOver
    }*/

    override fun onClick(v: View?) {
        when (v) {
            //替换采血管
            imgTH -> {
                if (checkSuccess == 3) {
                    showToast("已紧急跳过")
                    return
                }

                isReplace = true

                if (!isOpen) {
                    scanOpen()
                }

                replaceCaiXueDialog.show(adapter.data) { bloodId, uid, position ->
                    showProgress()
                    model.replace("$bloodId", uid, {
                        dismissProgress()
                        isReplace = false
                        showToast("替换成功")
                        adapter.data[position].rfidCode = uid
                    }, {
                        dismissProgress()
                        showToast(it)
                    })
                }
            }

            //开始核验
            tvStartCheck -> {
                if (checkSuccess == 2 || checkSuccess == 3) {
                    return
                }
                isHasClick = true
                if (isOpen) {
                    isOpen = false
                    tvStartCheck.text = "点击核验"
                    ScanUtils.close()
                    SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                } else {
                    if (!isCaiXue) {
                        //groupHY.visibility = View.INVISIBLE
                        tvStartCheck.text = "停止核验"
                        tvYear.text = "${TimeUtils.getNowString(SimpleDateFormat("yyyy"))}\n${
                            TimeUtils.getNowString(SimpleDateFormat("MM-dd"))
                        }"
                        scanOpen()
                    }
                }
            }

            //紧急跳过
            imgJump -> {
                if (isCaiXue || checkSuccess == 1 || checkSuccess == 2) {
                    showToast("已采血，无法跳过")
                    return
                }

                if (checkSuccess == 3) {
                    showToast("已紧急跳过")
                    return
                }

                showProgress()
                model.caixueJump("$drawBloodId") {
                    dismissProgress()
                    imgStation.setBackgroundResource(R.drawable.icon_jjtg)
                    tvStation.text = "紧急跳过"
                    tvStation.setTextColor(getColor(R.color.orange))
                    progressGroup.visibility = View.INVISIBLE
                    imgRed.visibility = View.GONE
                    groupHY.visibility = View.GONE
                    groupHYState.visibility = View.VISIBLE
                }
            }

            //下一个受试者
            imgNext -> {
                if (!isHasClick){
                    //没有点击过核验按钮，那么就不用判断是否记录采样时间了
                    startActivity(NFCActivity::class.java)
                    finish()
                    return
                }
                var checkCount = 0
                llStartTime.forEach { childView ->
                    val tvStartTime = childView.findViewById<TextView>(R.id.tvStartTime)
                    LogUtils.i(tvStartTime.text)
                    if(tvStartTime.text.toString().contains("采血时间")){
                        checkCount++
                    }
                }
                if(checkCount == llStartTime.childCount){
                    startActivity(NFCActivity::class.java)
                    finish()
                }else{
                    showToast("请记录采样时间")
                }
            }

            //扫描核验
            imgScan -> {
                if (checkSuccess == 0) {
                    val intent = Intent(this, ScanZBarActivity::class.java)
                    startActivityForResult(intent, 101)
                }
            }

            //查看采样点
            imgCYD -> {
                val intent = Intent(this, FormRecordActivity::class.java)
                intent.putExtra("uid", drawBloodOrderId)
                startActivity(intent)
                finish()
            }
        }
    }

    //扫码
    private fun scanOpen() {
        if (Build.MODEL == "V9100") {
            isOpen = true
            ScanUtils.open { uid ->
                SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                isBarCode = false
                startCheck(uid)
            }
        }
    }

    private fun collectBloodTime() {
        isCaiXue = true
        SoundUtils.playSound(SoundUtils.RECORD_TIME)
        groupHYState.visibility = View.VISIBLE
        if (TimeUtils.getNowMills() > preTime && TimeUtils.getNowMills() < afterTime) {
            //采血正常
            imgStation.setBackgroundResource(R.drawable.icon_heyan_success)
            tvStation.text = "采样正常"
        } else {
            imgStation.setBackgroundResource(R.drawable.icon_chaochuang)
            tvStation.text = "采样超窗"
            tvStation.setTextColor(getColor(R.color.red))
        }

        tvPlanCXTime.text = "计划采血时间:${tvPlanTime.text}"
        progressGroup.visibility = View.INVISIBLE
        imgRed.visibility = View.GONE
    }

    //开始核验
    private fun startCheck(uid: String) {

        ScanUtils.resetItem(uid)

        if (isReplace) {
            replaceCaiXueDialog.setUID(uid)
            return
        }

        adapter.data.forEachIndexed { index, item ->
            if (uid == item.rfidCode || uid == item.barCode) {
                SoundUtils.playSound(SoundUtils.CHECK_SUCCESS)
                item.scanTime = TimeUtils.getNowString(SimpleDateFormat("HH:mm:ss"))
                adapter.notifyItemChanged(index)
                if (isCheckAll()) {
                    submitData()
                    updateClickColor()
                }
                //核验正确 不往下走了
                return
            }
        }

        //核验错误，通过接口获取试管的名字，弹框提示
        showProgress()
        var noUid = ""
        adapter.data.forEach {
            if (noUid == "") {
                noUid = it.name ?: "--"
            } else {
                noUid = "$noUid\n${it.name}"
            }
        }
        if (isBarCode) {
            //数据来自条形码
            model.searchNameByBarCode(arrayListOf(uid), {
                dismissProgress()
                BloodScanErrorDialog(this).show(noUid, it[0])
                ScanUtils.resetItem(uid)
            }, {
                ScanUtils.resetItem(uid)
                dismissProgress()
                showToast(it)
            })
        } else {
            model.searchName(arrayListOf(uid), {
                dismissProgress()
                BloodScanErrorDialog(this).show(noUid, it[0])
                ScanUtils.resetItem(uid)
            }, {
                ScanUtils.resetItem(uid)
                dismissProgress()
                showToast(it)
            })
        }
        SoundUtils.playSound(SoundUtils.CHECK_ERROR)
    }

    /**
     * 核验完成之后，让 【点击记录采血时间】 按钮高亮显示
     */
    private fun updateClickColor() {
        /*llStartTime.forEach {
            val tvStartTime = it.findViewById<TextView>(R.id.tvStartTime)
            val lineCY = it.findViewById<View>(R.id.lineCY)
            val imgCY = it.findViewById<ImageView>(R.id.imgCY)

            tvStartTime.setBackgroundResource(R.drawable.shape_rect_red)
            tvStartTime.setTextColor(Color.RED)
            lineCY.setBackgroundColor(Color.RED)
            imgCY.setBackgroundResource(R.drawable.icon_time_red)
        }*/
    }

    //核验完毕  提交核验时间
    private fun submitData() {
        isAllChecked = true
        //全部核验完毕 关闭扫码
        isOpen = false
        tvStartCheck.text = "点击核验"
        ScanUtils.close()
        var id = ""
        adapter.data.forEach {
            if (id == "") {
                id = "${it.id}"
            } else {
                id = "$id,${it.id}"
            }
        }
        //核验完毕之后，开始倒计时
        if (checkSuccess == 0) {
            startDownTime()
        }
        model.recordCheckTime(id) {
            showToast("已记录核验时间")
        }
    }

    override fun onResume() {
        super.onResume()
        if (!isNFC) return
        //开启前台调度系统
        NFCUtils.mNfcAdapter.enableForegroundDispatch(
            this,
            NFCUtils.mPendingIntent,
            NFCUtils.mIntentFilter, NFCUtils.mTechList
        )
    }

    override fun onPause() {
        super.onPause()
        if (!isNFC) return
        //关闭前台调度系统
        NFCUtils.mNfcAdapter.disableForegroundDispatch(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101) {
            val uid = data?.getStringExtra("resultUid")
            if (uid == null) return
            isBarCode = true
            startCheck(uid)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (!isNFC) return
        //当该Activity接收到NFC标签时，运行该方法
        //调用工具方法，读取NFC数据
        var uid: String = NFCUtils.readNFCId(intent)
        uid = UIDUitls.sort(uid)
        isBarCode = false
        startCheck(uid)
    }

    fun isCheckAll(): Boolean {
        val bean = adapter.data.find { it.scanTime == null || it.scanTime == "" }
        if (bean == null) {
            return true
        } else {
            return false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isOpen) {
            ScanUtils.close()
            isOpen = false
        }
        if (disposable?.isDisposed == false) {
            disposable?.dispose()
        }
        if (disposable2?.isDisposed == false) {
            disposable2?.dispose()
        }
        if (disposable3?.isDisposed == false) {
            disposable3?.dispose()
        }
        // ScanUtils.onDestroy()
    }

}
